<template>
  <div class="my-apps-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">我的应用</h1>
        <p class="page-subtitle">管理和查看你创建的所有应用</p>
      </div>
      <div class="header-actions">
        <a-button type="primary" @click="createNewApp" class="create-btn">
          <template #icon>
            <PlusOutlined />
          </template>
          创建应用
        </a-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <a-card class="search-card">
        <a-row :gutter="16" align="middle">
          <a-col :xs="24" :sm="12" :md="8">
            <a-input-search
              v-model:value="searchForm.appName"
              placeholder="搜索应用名称..."
              @search="handleSearch"
              @pressEnter="handleSearch"
              class="search-input"
            >
              <template #prefix>
                <SearchOutlined class="search-icon" />
              </template>
            </a-input-search>
          </a-col>
          <a-col :xs="24" :sm="12" :md="6">
            <a-select
              v-model:value="searchForm.codeGenType"
              placeholder="应用类型"
              allow-clear
              @change="handleSearch"
              class="type-select"
            >
              <a-select-option
                v-for="option in codeGenTypeOptions"
                :key="option.value"
                :value="option.value"
              >
                {{ option.label }}
              </a-select-option>
            </a-select>
          </a-col>
          <a-col :xs="24" :sm="24" :md="10">
            <div class="search-actions">
              <a-button @click="handleReset" class="reset-btn"> 重置 </a-button>
              <a-button type="primary" @click="handleSearch" class="search-btn"> 搜索 </a-button>
            </div>
          </a-col>
        </a-row>
      </a-card>
    </div>

    <!-- 应用列表 -->
    <div class="apps-section">
      <a-card class="apps-card">
        <!-- 统计信息 -->
        <div class="stats-bar">
          <div class="stats-info">
            <span class="total-count">共找到 {{ total }} 个应用</span>
          </div>
          <div class="view-toggle">
            <a-radio-group v-model:value="viewMode" @change="handleViewModeChange">
              <a-radio-button value="grid">
                <AppstoreOutlined />
              </a-radio-button>
              <a-radio-button value="list">
                <BarsOutlined />
              </a-radio-button>
            </a-radio-group>
          </div>
        </div>

        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" class="grid-view">
          <a-row :gutter="[16, 16]">
            <a-col v-for="app in appsList" :key="app.id" :xs="24" :sm="12" :md="8" :lg="6">
              <div class="app-card" @click="viewApp(app)">
                <div class="app-cover">
                  <img v-if="app.cover" :src="app.cover" :alt="app.appName" class="cover-image" />
                  <div v-else class="cover-placeholder">
                    <CodeOutlined class="placeholder-icon" />
                  </div>
                  <div class="app-status" :class="getStatusClass(app)">
                    {{ getStatusText(app) }}
                  </div>
                </div>
                <div class="app-info">
                  <h3 class="app-name" :title="app.appName">{{ app.appName || '未命名应用' }}</h3>
                  <p class="app-desc" :title="app.initPrompt">{{ app.initPrompt || '暂无描述' }}</p>
                  <div class="app-meta">
                    <span class="app-type">{{ getTypeLabel(app.codeGenType) }}</span>
                    <span class="create-time">{{ formatTime(app.createTime) }}</span>
                  </div>
                  <div class="app-actions" @click.stop>
                    <a-button type="text" size="small" @click="editApp(app)">
                      <template #icon>
                        <EditOutlined />
                      </template>
                    </a-button>
                    <a-button
                      type="text"
                      size="small"
                      @click="deployApp(app)"
                      v-if="!app.deployKey"
                    >
                      <template #icon>
                        <CloudUploadOutlined />
                      </template>
                    </a-button>
                    <a-button type="text" size="small" @click="openApp(app)" v-else>
                      <template #icon>
                        <LinkOutlined />
                      </template>
                    </a-button>
                    <a-dropdown>
                      <a-button type="text" size="small">
                        <template #icon>
                          <MoreOutlined />
                        </template>
                      </a-button>
                      <template #overlay>
                        <a-menu>
                          <a-menu-item @click="downloadApp(app)">
                            <template #icon>
                              <DownloadOutlined />
                            </template>
                            下载代码
                          </a-menu-item>
                          <a-menu-divider />
                          <a-menu-item @click="deleteApp(app)" class="danger-menu-item">
                            <template #icon>
                              <DeleteOutlined />
                            </template>
                            删除应用
                          </a-menu-item>
                        </a-menu>
                      </template>
                    </a-dropdown>
                  </div>
                </div>
              </div>
            </a-col>
          </a-row>
        </div>

        <!-- 列表视图 -->
        <div v-if="viewMode === 'list'" class="list-view">
          <a-table
            v-if="!loading && appsList.length > 0"
            :columns="tableColumns"
            :data-source="appsList"
            :pagination="false"
            row-key="id"
            @row="handleRowClick"
            :scroll="{ x: 800 }"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'appName'">
                <div class="app-name-cell">
                  <div class="app-cover-small">
                    <img v-if="record.cover" :src="record.cover" :alt="record.appName" />
                    <CodeOutlined v-else />
                  </div>
                  <div class="app-info-text">
                    <div class="name">{{ record.appName || '未命名应用' }}</div>
                    <div class="desc">{{ record.initPrompt || '暂无描述' }}</div>
                  </div>
                </div>
              </template>
              <template v-if="column.key === 'status'">
                <a-tag :color="getStatusColor(record)">
                  {{ getStatusText(record) }}
                </a-tag>
              </template>
              <template v-if="column.key === 'codeGenType'">
                <a-tag>{{ getTypeLabel(record.codeGenType) }}</a-tag>
              </template>
              <template v-if="column.key === 'createTime'">
                {{ formatTime(record.createTime) }}
              </template>
              <template v-if="column.key === 'actions'">
                <div class="table-actions">
                  <a-button type="link" size="small" @click.stop="editApp(record)"> 编辑 </a-button>
                  <a-button
                    type="link"
                    size="small"
                    @click.stop="deployApp(record)"
                    v-if="!record.deployKey"
                  >
                    部署
                  </a-button>
                  <a-button type="link" size="small" @click.stop="openApp(record)" v-else>
                    打开
                  </a-button>
                  <a-dropdown placement="bottomRight">
                    <a-button type="link" size="small" @click.stop>
                      更多
                      <DownOutlined />
                    </a-button>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item @click="downloadApp(record)">下载代码</a-menu-item>
                        <a-menu-divider />
                        <a-menu-item @click="deleteApp(record)" class="danger-menu-item"
                          >删除应用</a-menu-item
                        >
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </template>
            </template>
          </a-table>

          <!-- 列表视图加载状态 -->
          <div v-if="loading" class="list-loading">
            <a-spin size="large" />
            <p>加载中...</p>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && appsList.length === 0" class="empty-state">
          <a-empty :image="Empty.PRESENTED_IMAGE_SIMPLE" description="暂无应用">
            <a-button type="primary" @click="createNewApp">
              <template #icon>
                <PlusOutlined />
              </template>
              创建第一个应用
            </a-button>
          </a-empty>
        </div>

        <!-- 分页器 -->
        <div v-if="appsList.length > 0" class="pagination-wrapper">
          <a-pagination
            v-model:current="currentPage"
            v-model:pageSize="pageSize"
            :total="total"
            :show-size-changer="false"
            :show-quick-jumper="true"
            :show-total="(total, range) => `第 ${range[0]}-${range[1]} 项，共 ${total} 项`"
            @change="handlePageChange"
          />
        </div>
      </a-card>
    </div>

    <!-- 编辑应用模态框 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑应用"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
      :confirm-loading="editLoading"
    >
      <a-form :model="editForm" layout="vertical">
        <a-form-item label="应用名称" required>
          <a-input v-model:value="editForm.appName" placeholder="请输入应用名称" :maxlength="50" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message, Modal, Empty } from 'ant-design-vue'
import {
  PlusOutlined,
  SearchOutlined,
  AppstoreOutlined,
  BarsOutlined,
  CodeOutlined,
  EditOutlined,
  CloudUploadOutlined,
  LinkOutlined,
  MoreOutlined,
  DownloadOutlined,
  DeleteOutlined,
  DownOutlined,
} from '@ant-design/icons-vue'
import {
  listMyAppVoByPage,
  updateApp,
  deleteApp as deleteAppApi,
  deployApp as deployAppApi,
  downloadAppCode,
} from '@/api/appController'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { getDeployUrl, API_BASE_URL } from '@/env'
import { CODE_GEN_TYPE_OPTIONS } from '@/utils/codeGenTypes'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 响应式数据
const loading = ref(false)
const appsList = ref<API.AppVO[]>([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const viewMode = ref<'grid' | 'list'>('grid')

// 搜索表单
const searchForm = reactive({
  appName: '',
  codeGenType: undefined as string | undefined,
})

// 编辑相关
const editModalVisible = ref(false)
const editLoading = ref(false)
const editForm = reactive({
  id: 0,
  appName: '',
})

// 代码生成类型选项
const codeGenTypeOptions = CODE_GEN_TYPE_OPTIONS

// 表格列配置
const tableColumns = [
  {
    title: '应用名称',
    key: 'appName',
    width: '35%',
  },
  {
    title: '状态',
    key: 'status',
    width: '12%',
  },
  {
    title: '类型',
    key: 'codeGenType',
    width: '15%',
  },
  {
    title: '创建时间',
    key: 'createTime',
    width: '18%',
  },
  {
    title: '操作',
    key: 'actions',
    width: '20%',
    fixed: 'right',
  },
]

// 获取应用状态文本
const getStatusText = (app: API.AppVO) => {
  if (app.deployKey) return '已部署'
  return '开发中'
}

// 获取状态样式类
const getStatusClass = (app: API.AppVO) => {
  if (app.deployKey) return 'deployed'
  return 'developing'
}

// 获取状态颜色
const getStatusColor = (app: API.AppVO) => {
  if (app.deployKey) return 'success'
  return 'processing'
}

// 获取类型标签
const getTypeLabel = (type?: string) => {
  const option = codeGenTypeOptions.find((opt) => opt.value === type)
  return option?.label || type || '未知'
}

// 格式化时间
const formatTime = (timeStr?: string) => {
  if (!timeStr) return '-'
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 获取应用列表
const fetchAppsList = async () => {
  try {
    loading.value = true
    const params: API.AppQueryRequest = {
      current: currentPage.value,
      pageSize: pageSize.value,
      sortField: 'createTime',
      sortOrder: 'desc',
    }

    if (searchForm.appName.trim()) {
      params.appName = searchForm.appName.trim()
    }

    if (searchForm.codeGenType) {
      params.codeGenType = searchForm.codeGenType
    }

    const res = await listMyAppVoByPage(params)

    if (res.data.code === 0) {
      appsList.value = res.data.data?.records || []
      total.value = res.data.data?.totalRow || 0
    } else {
      message.error('获取应用列表失败：' + res.data.message)
    }
  } catch (error) {
    console.error('获取应用列表失败:', error)
    message.error('获取应用列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchAppsList()
}

// 重置搜索
const handleReset = () => {
  searchForm.appName = ''
  searchForm.codeGenType = undefined
  currentPage.value = 1
  fetchAppsList()
}

// 分页处理
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchAppsList()
}

// 视图模式切换
const handleViewModeChange = () => {
  // 可以保存用户偏好到localStorage
  localStorage.setItem('myAppsViewMode', viewMode.value)
}

// 表格行点击
const handleRowClick = (record: API.AppVO) => {
  return {
    onClick: () => viewApp(record),
  }
}

// 创建新应用
const createNewApp = () => {
  router.push('/')
}

// 查看应用详情
const viewApp = (app: API.AppVO) => {
  router.push(`/app/${app.id}`)
}

// 编辑应用
const editApp = (app: API.AppVO) => {
  editForm.id = app.id!
  editForm.appName = app.appName || ''
  editModalVisible.value = true
}

// 提交编辑
const handleEditSubmit = async () => {
  if (!editForm.appName.trim()) {
    message.warning('请输入应用名称')
    return
  }

  try {
    editLoading.value = true
    const res = await updateApp({
      id: editForm.id,
      appName: editForm.appName.trim(),
    })

    if (res.data.code === 0) {
      message.success('更新成功')
      editModalVisible.value = false
      fetchAppsList()
    } else {
      message.error('更新失败：' + res.data.message)
    }
  } catch (error) {
    console.error('更新应用失败:', error)
    message.error('更新失败，请稍后重试')
  } finally {
    editLoading.value = false
  }
}

// 取消编辑
const handleEditCancel = () => {
  editModalVisible.value = false
  editForm.id = 0
  editForm.appName = ''
}

// 部署应用
const deployApp = async (app: API.AppVO) => {
  try {
    const res = await deployAppApi({ appId: app.id! })
    if (res.data.code === 0) {
      message.success('部署成功！')
      fetchAppsList()
    } else {
      message.error('部署失败：' + res.data.message)
    }
  } catch (error) {
    console.error('部署失败:', error)
    message.error('部署失败，请稍后重试')
  }
}

// 打开应用
const openApp = (app: API.AppVO) => {
  if (app.deployKey) {
    const url = getDeployUrl(app.deployKey)
    window.open(url, '_blank')
  }
}

// 下载应用代码
const downloadApp = async (app: API.AppVO) => {
  try {
    const link = document.createElement('a')
    link.href = `${API_BASE_URL}/app/download/${app.id}`
    link.download = `${app.appName || 'app'}.zip`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载失败:', error)
    message.error('下载失败，请稍后重试')
  }
}

// 删除应用
const deleteApp = (app: API.AppVO) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除应用"${app.appName || '未命名应用'}"吗？此操作不可恢复。`,
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    onOk: async () => {
      try {
        const res = await deleteAppApi({ id: app.id! })
        if (res.data.code === 0) {
          message.success('删除成功')
          fetchAppsList()
        } else {
          message.error('删除失败：' + res.data.message)
        }
      } catch (error) {
        console.error('删除应用失败:', error)
        message.error('删除失败，请稍后重试')
      }
    },
  })
}

// 组件挂载
onMounted(() => {
  // 恢复用户偏好的视图模式
  const savedViewMode = localStorage.getItem('myAppsViewMode')
  if (savedViewMode === 'list' || savedViewMode === 'grid') {
    viewMode.value = savedViewMode
  }

  fetchAppsList()
})
</script>

<style lang="scss" scoped>
.my-apps-page {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 24px;

  .header-content {
    .page-title {
      font-size: 28px;
      font-weight: 700;
      margin: 0 0 8px 0;
      color: #333;
    }

    .page-subtitle {
      font-size: 16px;
      color: #666;
      margin: 0;
    }
  }

  .header-actions {
    .create-btn {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      border: none;
      height: 40px;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
      }
    }
  }
}

.search-section {
  margin-bottom: 24px;

  .search-card {
    border-radius: 12px;

    .search-input {
      .search-icon {
        color: #999;
      }
    }

    .search-actions {
      display: flex;
      gap: 8px;
      justify-content: flex-end;

      .search-btn {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border: none;
      }
    }
  }
}

.apps-section {
  .apps-card {
    border-radius: 12px;

    .stats-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 24px;
      padding-bottom: 16px;
      border-bottom: 1px solid #f0f0f0;

      .stats-info {
        .total-count {
          color: #666;
          font-size: 14px;
        }
      }
    }
  }
}

.grid-view {
  .app-card {
    background: white;
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.3s ease;
    cursor: pointer;
    border: 1px solid #f0f0f0;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
      border-color: #667eea;
    }

    .app-cover {
      height: 160px;
      position: relative;
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      display: flex;
      align-items: center;
      justify-content: center;

      .cover-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .cover-placeholder {
        .placeholder-icon {
          font-size: 48px;
          color: #ddd;
        }
      }

      .app-status {
        position: absolute;
        top: 12px;
        right: 12px;
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;

        &.deployed {
          background: #f6ffed;
          color: #52c41a;
          border: 1px solid #b7eb8f;
        }

        &.developing {
          background: #e6f7ff;
          color: #1890ff;
          border: 1px solid #91d5ff;
        }
      }
    }

    .app-info {
      padding: 16px;

      .app-name {
        font-size: 16px;
        font-weight: 600;
        margin: 0 0 8px 0;
        color: #333;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .app-desc {
        color: #666;
        font-size: 14px;
        line-height: 1.5;
        margin: 0 0 12px 0;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;
        min-height: 42px;
      }

      .app-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 12px;
        color: #999;
        margin-bottom: 12px;

        .app-type {
          background: #f0f0f0;
          color: #666;
          padding: 2px 6px;
          border-radius: 6px;
        }
      }

      .app-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 8px;
        border-top: 1px solid #f0f0f0;

        .ant-btn {
          color: #666;

          &:hover {
            color: #667eea;
          }
        }
      }
    }
  }
}

.list-view {
  .app-name-cell {
    display: flex;
    align-items: center;
    gap: 12px;

    .app-cover-small {
      width: 40px;
      height: 40px;
      border-radius: 8px;
      overflow: hidden;
      background: #f5f5f5;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .anticon {
        color: #999;
        font-size: 18px;
      }
    }

    .app-info-text {
      flex: 1;
      min-width: 0;

      .name {
        font-weight: 500;
        color: #333;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .desc {
        font-size: 12px;
        color: #999;
        margin-top: 4px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }

  .table-actions {
    display: flex;
    gap: 4px;
    align-items: center;
    flex-wrap: nowrap;
    justify-content: flex-start;
    min-width: 120px;

    .ant-btn {
      padding: 0 8px;
      font-size: 12px;
      white-space: nowrap;
    }
  }

  .list-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 60px 0;

    p {
      margin-top: 16px;
      color: #666;
      font-size: 14px;
    }
  }
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

.pagination-wrapper {
  margin-top: 32px;
  text-align: center;

  :deep(.ant-pagination) {
    .ant-pagination-item {
      border-radius: 6px;

      &.ant-pagination-item-active {
        background: #667eea;
        border-color: #667eea;

        a {
          color: white;
        }
      }
    }

    .ant-pagination-prev,
    .ant-pagination-next {
      border-radius: 6px;
    }
  }
}

:deep(.danger-menu-item) {
  color: #ff4d4f !important;

  &:hover {
    background: #fff2f0 !important;
  }

  .anticon {
    color: #ff4d4f !important;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .my-apps-page {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;

    .header-content .page-title {
      font-size: 24px;
    }
  }

  .search-section {
    .search-actions {
      justify-content: center;
      margin-top: 16px;
    }
  }

  .stats-bar {
    flex-direction: column;
    align-items: flex-start !important;
    gap: 16px;
  }

  .view-toggle {
    align-self: stretch;
  }
}

@media (max-width: 576px) {
  .grid-view {
    .ant-col {
      // 移动端每行显示1个
      width: 100% !important;
      max-width: none !important;
    }
  }

  .app-actions {
    flex-wrap: wrap;
    gap: 8px;
  }
}
</style>
